<template>
  <div class="app-container">
      <div class="title-wrapper">车辆保险管理</div>
      <div class="page-main">
      <div shadow="never" class="search-wrapper" v-permission="['insurance-search']">
        <div class="search-main">
          <el-form ref="searchFormRef" :inline="true" :model="searchData">
            <el-form-item prop="carNo" label="车牌号">
              <el-input v-model="searchData.carNo" placeholder="请输入车牌号" clearable/>
            </el-form-item>
          </el-form>
        </div>
        <div class="search-btn">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </div>
      </div>
      <div class="toolbar-wrapper">
          <el-button type="primary" v-permission="['insurance-add']" @click="handleAdd">新增</el-button>
      </div>

      <div v-loading="loading"  class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column sortable prop="carNo" label="车牌号"  />
          <el-table-column sortable prop="expireDate" label="保险到期日"  />
          <el-table-column sortable prop="price" label="费用"  />
          <el-table-column sortable prop="type" label="保险类型"  />
          <el-table-column sortable prop="company" label="保险公司"  />
          <el-table-column sortable prop="mobile" label="保险公司联系电话"  />
          <!-- <el-table-column sortable prop="attachmentName" label="附件名称"  /> -->
          <el-table-column fixed="right" label="操作" width="150" >
            <template #default="scope">
              <!-- <el-button type="primary" v-permission="['insurance-view']" text size="small" @click="handleDownload(scope.row.attachment)">查看附件</el-button> -->
              <el-button type="primary" v-permission="['insurance-edit']" text size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" v-permission="['insurance-del']" text size="small" @click="handleoneDelete(deleteCarInsuranceById, scope.row.carInsuranceId, `${scope.row.carNo}的车辆保险数据`)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
  <gm-dialog v-if="dialogVisible"
    ref="dialogRef"
    :title="form&&form.carInsuranceId?'新增车辆保险':'新增车辆保险'"
    @cancel="closeHandle"
    @comfirm="successHandle">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="140px" label-position="left">
      <el-form-item prop="carId" label="车辆">
        <carSelect v-model="form.carId" :multiple="false" width="100%" @change="handleChange"></carSelect>
      </el-form-item>
      <el-form-item  prop="company" label="保险公司">
        <el-input v-model="form.company" placeholder="请输入" />
      </el-form-item>
      <el-form-item  prop="type" label="保险类型">
        <el-input v-model="form.type" placeholder="请输入" />
      </el-form-item>
      <el-form-item prop="mobile" label="保险公司联系电话">
        <el-input v-model="form.mobile" placeholder="请输入" />
      </el-form-item>
      <el-form-item prop="expireDate" label="保险到期日">
        <el-date-picker
          v-model="form.expireDate"
          type="date"
          placeholder="请选择"
          style="width:100%;"
          format="YYYY-MM-DD" value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item  prop="price" label="费用">
        <el-input v-model="form.price" placeholder="请输入" />
      </el-form-item>

      <el-form-item label="图片" prop="pics">
        <el-upload
          ref="fileUploadBtn"
          class="avatar-uploader"
          :action="uploadUrl"
          :file-list="fileArr"
          :on-change="imgPreview"
          :on-preview="handlePreview"
          :show-file-list="false"
          :on-success="handleUploadSuccess"
          accept="image/jpeg, image/png"
          :auto-upload="true"
          :on-remove="handleRemove">
          <el-icon class="upload-img-action"><Plus /></el-icon>
        </el-upload>
        <div class="form-value-flex" v-if="form.pics&&form.pics.length>0">
          <uploadImage v-for="item in form.pics" :src="item" @del="handleUploadDel(item)" class="upload-img-image" />
        </div>
      </el-form-item>
      <!-- <el-form-item  prop="attachmentName" label="附件名称">
        <el-input v-model="form.attachmentName" placeholder="请输入" />
      </el-form-item> -->

    </el-form>
  </gm-dialog>
</template>
<script lang="ts" setup>
  import { ref, watch,reactive,nextTick } from "vue"
  import { type FormInstance, ElMessage, ElMessageBox,type FormRules } from "element-plus"
  import { genFileId } from 'element-plus'
  import type { UploadProps, UploadUserFile } from 'element-plus'
  import { getCarInsuranceList, deleteCarInsuranceById,saveOrUpdateCarInsurance,getCarInsuranceDetails } from "@/api/vehicle/carInsurance"
  import {validateIdcard, validatePhone} from '@/utils/validate'
  import { usePagination } from "@/hooks/usePagination"
  import useTable from '@/hooks/useTable'
  import gmDialog from '@/components/Dialog/index.vue'
  import useForm from '@/hooks/useForm'
  import { cloneDeep } from "lodash-es"
  import carSelect from '@/components/carSelect/index.vue'
  import useFile from '@/hooks/useFile'

  let fileUploadBtn =ref<any>()
  const loading = ref<boolean>(false)
  const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
  const tableData = ref<any>([])
  const dialogVisible = ref<boolean>(false)
  const searchFormRef = ref<FormInstance | null>(null)
  const searchData = reactive<any>({})

  const form = ref<any>({})
  const formRef = ref<FormInstance>()
  const dialogRef = ref<InstanceType<typeof gmDialog>>()

  const { beforeAvatarUpload, uploadUrl, uploadImage } = useFile({ maxSize: 30, fileType: 'image' })

  const fileArr = ref<any>([])
  const rules: FormRules = {
    company: [
      { required: true, message: '请输入保险公司', trigger: 'change' },
    ],
    mobile: [
      { required: true, message: '请输入保险公司联系电话', trigger: 'change' },
      // { validator: validatePhone, trigger: 'change' }
    ],
    expireDate: [
      { required: true, message: '请输入保险到期日', trigger: 'change' },
    ],
    price: [
      { required: true, message: '请输入费用', trigger: 'change' },
      { pattern: /^\d+(\.\d+)?$/, message: '请输入数字', trigger: 'change' }
    ],
    carId: [
      { required: true, message: '请输入车辆', trigger: 'change' },
    ],
    carNo: [
      { required: true, message: '请输入车牌号', trigger: 'change' },
    ],
    pics: [
      { required: true, message: '请上传图片', trigger: 'change' },
    ],
    // attachmentName: [
    //   { required: true, message: '请输入附件名称', trigger: 'change' },
    // ],
  }

  const getTableData = () => {
    loading.value = true
    getCarInsuranceList({
      ...paginationData,
      ...searchData
    }).then((res: any) => {
      paginationData.total = res.totalCount
      tableData.value = res.data
    }).catch(() => {
      tableData.value = []
    }).finally(() => {
      loading.value = false
    })
  }

  const {handleoneDelete } = useTable({getList:getTableData})

  const handleUpdate = (row: any) => {
    getCarInsuranceDetails({id:row.carInsuranceId}).then((res: any) => {
      form.value = res
      nextTick(()=>{
        form.value.carId =res.carId
        form.value.pics = res.attachment ? res.attachment.split(',') : []
      })
      dialogVisible.value = true
    }).catch(() => {

    }).finally(() => {
      loading.value = false
    })

  }
  const imgPreview = (file: any) => {
      fileArr.value = [];
      fileArr.value.push(file);
      form.value.position = "";
      console.log(file);
      form.value.position = file.name;
      let fileName = file.name;
      let regex = /(.jpg|.jpeg|.gif|.png|.pdf)$/;
      if (regex.test(fileName.toLowerCase())) {
        console.log(URL.createObjectURL(file.raw), 1111);
      } else {
        ElMessage.error("请选择图片文件");
      }
    }

  const handleUploadDel = (src: string) => {
    console.log(src, 'sev', form.value.pics)
    form.value.pics = form.value.pics.filter((i) => i !== src)
  }

  const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
    console.log(uploadFile)
  }

  const handleAdd = () => {
    form.value = {
      pics:[]
    }
    dialogVisible.value = true
  }

  const closeHandle = () => {
    dialogVisible.value = false
  }

  const handleSearch = () => {
    paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
  }

  const handleDownload = (attachmentUrl: string) => {
    if (attachmentUrl) {
      window.open(attachmentUrl, '_blank');
    } else {
      ElMessage({
        message: '没有可用的附件',
        type: 'warning',
      });
    }
  };

  const resetSearch = () => {
    searchFormRef.value?.resetFields()
    handleSearch()
  }

  const successHandle = () => {
    form.value.attachment = form.value.pics.join(',')
    let newForm={
      carInsuranceId:form.value.carInsuranceId,
      carId:form.value.carId,
      carNo:form.value.carNo,
      price:form.value.price,
      mobile:form.value.mobile,
      attachment:form.value.attachment,
      expireDate:form.value.expireDate,
      company:form.value.company,
      attachmentName:form.value.attachmentName,
      type:form.value.type,
    }
    handleSubmit(saveOrUpdateCarInsurance, formRef.value, newForm, dialogRef.value)
  }

  const handleSubmit = async(api: any, formEl:any,  formData: any, gmRef:any = null) => {
    await formEl.validate((valid: any) => {
      if (!valid) {
        return
      }
      gmRef.setLoading(true)
      api(formData).then((res: any)=>{
        ElMessage({
          message: '操作成功',
          type: 'success',
        })
        dialogVisible.value = false
        getTableData()
        gmRef.setLoading(false)
      }).catch(()=>{
        gmRef.setLoading(false)
      })
    })
  }

  const handleUploadSuccess = (res: any, file: any,fileArr:any) => {
    form.value.pics.push(res.result)
    nextTick(() => {
      // 清空上传组件的文件列表
      if (fileUploadBtn.value) {
        fileUploadBtn.value.clearFiles();
        // 重置 input 的值，确保下次选择相同文件也能触发
        const input = fileUploadBtn.value.$el.querySelector('input[type="file"]') as HTMLInputElement;
        if (input) {
          input.value = '';
        }
      }
    });
  }

  const handleRemove = (file: UploadUserFile) => {
    const index = form.value.pics.indexOf(file.name);
    if (index > -1) {
      form.value.pics.splice(index, 1);
    }
  }

  const handleChange = (e: any)=>{
    console.log(e,'eeeee')
    form.value.carNo=e.carNo
  }
  watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>
<style lang="scss" scoped>
.pdfstyle{
  color:#D68E44;
  text-decoration:underline;
  cursor: pointer;
}
</style>
